const path = require('path');
const { sep } = path;
const glob = require('glob');
/**
 * 加载控制器
 * @param {*} app Elpis应用实例
 */
module.exports = (app) => {
    const controllerPath = path.resolve(app.bisinessPath, `.${sep}controllers`);
    const fileList = glob.sync(path.resolve(controllerPath, `.${sep}**${sep}**.js`));

    const controllers = {}
    fileList.forEach((file) => {
        let name = path.resolve(file)
        name = name.substring(name.lastIndexOf(`controllers${sep}`) + `controllers${sep}`.length, name.lastIndexOf('.'))
        name = name.replace(/[_-][a-z]/ig, (s) => s.substring(1).toUpperCase())

        let tempController = controllers
        const names = name.split(sep);
        names.forEach((n, i) => {
            if (i == names.length - 1) {
                const controllermodule = require(path.resolve(file))(app)
                tempController[names[i]] = new controllermodule()
            } else {
                if (!tempController[names[i]]) {
                    tempController[names[i]] = {}
                }
                tempController = tempController[names[i]]
            }
        })
    });
    app.controllers = controllers;
}